import React, { PureComponent } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Form, Button, Select, Tree, Col, Row, Cascader, message, Modal } from 'antd';
import { getStudentSubject, getTestNum, clearRecord, getTestPaper, submitPracticePaper } from '@/services/studentPractice'
import { getHandle } from '@/services/baseurl'
import { settingShow, exercisePoints } from '@/services/setting'
import {  checkHost,isLianxi } from '@/utils/utils'
import { history } from 'umi'
const layout = {
    labelCol: { span: 0 },
    wrapperCol: { span: 10 },
};
class Index extends PureComponent<any, any> {
    constructor(props: any) {
        super(props)
        // const {type,p_type,subject} = props.location.query
        const userinfo = JSON.parse(localStorage.getItem('userinfo') || '{}');
        const hasTwo:any = localStorage.getItem('hasTwo')||2;
        const openid = userinfo.openid;
        if (checkHost()) {
            if (!openid&&hasTwo!=1) {
                Modal.confirm({
                    title: <p style={{ fontSize: 20, marginTop: -3 }}>操作提醒</p>,
                    content: <p style={{ fontSize: 18 }}>新用户请绑定您的微信账号解锁培训练习权限，绑定成功后每次登录平台请使用微信进行扫码登录即可。</p>,
                    okText: '去绑定',
                    style: { fontSize: 30, color: "#f60" },
                    onOk: () => {
                        location.href = `/index/index/login_weixin`;
                    },
                });
                history.goBack();
            }
        }


        this.state = {
            treeData: [],
            cascaderData: [],
            subject: '',
            type: '',
            p_type: '',
            testNum: {},
            question_p_type: '',
            question_type: '',
            question_subject: '',
            exercise_num: 0,
            loading: false
        }
    }
    submitHandle = () => {
        const scrWidth = screen.availWidth - 20;
        const scrHeight = screen.availHeight - 40;
        const { subject, type, p_type, question_p_type, question_subject, question_type, exercise_num, testNum } = this.state;
        if (!subject || !type || !p_type) return message.error('请先选择考题信息');
        this.setState({
            loading: true
        })
        const uid = localStorage.getItem('id');
        const wrongs = testNum.n_num < exercise_num ? testNum.wrongs : null;
        const userinfo = JSON.parse(localStorage.getItem('userinfo') || '{}');
        getTestPaper({ type, subject, p_type, uid, wrongs }).then(res => {
            if (!res[0]) {
                this.setState({
                    loading: false
                })
                if (res.status === '积分不够') return message.error('积分不足')
                return message.error('本题型题库试题已答完，您可以选择其他题型继续做答，或者清除答题记录重新做答')
            }
            exercisePoints(uid).then(res => {
                this.setState({
                    loading: false
                })
                if (res.status === '积分不够') return message.error('积分不足')
                const uid = localStorage.getItem('id')||'';
                const operation = userinfo.name + `进入了专项练习（${question_subject[0]},${question_type},${question_p_type}）`
                getHandle({ operation })
                submitPracticePaper({
                    wrongAnswers: [],
                    uid,
                    allIds: [],
                    correctAnswers: [],
                    marked: [],
                    rightAnswers: [],
                    type,
                    all: 0,
                    subject,
                    wrong_num: 0,
                    wrong_done: [],
                    wrong_done_right: [],
                    right_num: 0,
                    time: 0,
                    complete: [],
                    id:''
                }).then(res => {
                    history.push(`/testPage/${type}/${subject}/${p_type}/${wrongs}/${question_subject[0]}/${question_type}/${question_p_type}/${res.id}`, "考试中心", "height=" + scrHeight + ", width=" + scrWidth + ", top=0, left=0,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no")
                })
                return
               
                // window.open(dev + `#/testPage/${type}/${subject}/${p_type}`, "考试中心", "height=" + scrHeight + ", width=" + scrWidth + ", top=0, left=0,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no");
            })
        })


    }
    transilate = (data: any) => {

        return data.map((item: any) => {

            if (item.children) {

                if (item.children.length > 0) {

                    let concatR = item.children1 ? item.children1.concat(item.children) : item.children

                    item.children1 = concatR

                }

                return this.transilate(item.children)

            }

            return item

        });

    }
    uniquel = (arr: any) => {
        let result = {};
        let finalResult = [];
        for (let i = 0; i < arr.length; i++) {
            result[arr[i].title] = arr[i];
        }
        for (let item in result) {
            finalResult.push(result[item]);
        }
        return finalResult;
    }
    componentDidMount() {
        const uid = localStorage.getItem('id') || '';
        getStudentSubject({ uid }).then(res => {
            if (!res.subjects) return;
            const treeData = res.subjects?JSON.parse(JSON.stringify(res.subjects).replace(/id/g, 'key')):[]
            const cascaderData = res.subjects?JSON.parse(JSON.stringify(res.subjects).replace(/id/g, 'value').replace(/title/g, 'label')):[]
            let newarr = [];
            for (let i = 0; i < treeData.length; i++) {
                newarr.push(treeData[i].parent)
            }
            newarr = this.uniquel(newarr)
            for (let i = 0; i < treeData.length; i++) {
                const children = treeData[i];
                for (let j = 0; j < newarr.length; j++) {
                    const item = newarr[j];
                    item.selectable = false;
                    if (children.pkey === item.key) {
                        if (item.children) {
                            item.children.push(children)
                        } else {
                            item.children = [children];
                        }
                    }
                    newarr[j].children && delete newarr[j].children.parent
                }
            }
            this.setState({
                treeData: newarr,
                cascaderData,
                subject: [res.subjects[0].id],
                question_subject: [res.subjects[0].title]
            })
            this.getTestNum('', res.subjects[0].id, '')
        })
        settingShow().then(res => {
            this.setState({
                exercise_num: res.exercise_num
            })
        })
    }
    changeSubject = (e: any, d: any) => {
        const { type, p_type } = this.state
        const data = d[0] ? d[d.length - 1].label : ''
        this.setState({
            subject: e[0] ? [e[e.length - 1]] : [],
            question_subject: data,
        })
        this.getTestNum(type, e, p_type)

    }
    changeType = (e: any, d: any) => {
        const { p_type, subject } = this.state
        this.setState({
            type: e,
            question_type: d.children
        })
        this.getTestNum(e, subject, p_type)
    }
    changePracticeType = (e: any, d: any) => {
        this.setState({
            p_type: e,
            question_p_type: d.children
        })
        const { type, subject } = this.state
        this.getTestNum(type, subject, e)
    }
    getTestNum = (type: any, subject: any, p_type: any) => {
        const uid = localStorage.getItem('id') || '';
        getTestNum({ type, subject, p_type, uid }).then(res => {
            this.setState({
                testNum: res
            })
        })
    }
    selectTree = (e: any, d: any) => {
        if (!e[0]) return;
        const { type, p_type } = this.state
        this.setState({
            subject: e,
            question_subject: d.node.title
        })
        this.getTestNum(type, e, p_type)
    }
    clearRecordHandle = () => {
        const uid = localStorage.getItem('id') || '';
        const { type, p_type, subject } = this.state
        Modal.confirm({
            title: <b style={{ fontSize: 18 }}>提示</b>,
            content: <p style={{ fontSize: 16 }}>确定要清除所有答题记录吗？清除后题库数据会重置为0，系统会重新记录您的答题情况。</p>,
            onOk: () => {
                clearRecord({ uid, subject }).then(res => {
                    if (res.status === 1) {
                        message.success('已清除');
                        this.getTestNum(type, subject, p_type)
                    }
                })
            }
        })
    }
    render() {
        const id_number = localStorage.getItem('id_number')
        const name = localStorage.getItem('name')
        const { treeData, cascaderData, subject, testNum, question_subject, question_type, type, p_type, exercise_num, loading } = this.state;
        return (
            <PageContainer>
                <Card>
                    <Row>
                        <Col span={6}>
                            {
                                treeData[0] && <Tree defaultExpandAll treeData={treeData} onSelect={this.selectTree} />
                            }
                        </Col>
                        <Col span={12}>
                            <div style={{ marginBottom: 25 }}>
                                <p>专项练习每次可以作答{exercise_num}道题，您可以有针对性的练习各类题型。</p>
                            </div>
                            <Form {...layout}>
                                <Form.Item label="准考证号">
                                    {id_number}
                                </Form.Item>
                                <Form.Item label="考生姓名">
                                    {name}
                                </Form.Item>
                                <Form.Item label="练习科目">
                                    <Cascader options={cascaderData} value={subject} onChange={this.changeSubject}></Cascader>
                                </Form.Item>
                                <Form.Item label="练习题型">
                                    <Select onChange={this.changeType} defaultValue="" value={type}>
                                        <Select.Option key="1" value="1">单选</Select.Option>
                                        {
                                            !isLianxi()&& <Select.Option key="2" value="2">多选</Select.Option>
                                        }
                                       
                                        <Select.Option key="3" value="3">判断</Select.Option>
                                    </Select>
                                </Form.Item>
                                {/* <Form.Item label="难易程度">
                                <Select>
                                        <Select.Option key="1" value="1">单选</Select.Option>
                                        <Select.Option key="2" value="2">多选</Select.Option>
                                        <Select.Option key="3" value="3">判断</Select.Option>
                                    </Select>
                                </Form.Item> */}
                                <Form.Item label="练习类别">
                                    <Select onChange={this.changePracticeType} value={p_type}>
                                        <Select.Option key="1" value="1">只做新题和错题</Select.Option>
                                        <Select.Option key="2" value="2">只做新题</Select.Option>
                                        <Select.Option key="3" value="3">只做错题</Select.Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item label="练习提示">
                                    {
                                        ((question_subject) && ` ${question_subject}${question_type ? `(${question_type})` : ''}，
                                        共${testNum.z_num}道，您已答${testNum.done}道（已作答题答对${testNum.w_num}道，
                                        答错${testNum.wrong}道，错题题库${testNum.wrongs}道），此类别题库内未答${testNum.n_num}道`)
                                    }


                                </Form.Item>
                            </Form>
                            <Row gutter={30}>
                                <Col><Button type="primary" loading={loading} onClick={this.submitHandle}>提交</Button></Col>
                                <Col><Button type="primary" onClick={this.clearRecordHandle} danger>清除答题记录</Button></Col>
                                {/* <Col><Button danger type="primary">清除记录</Button></Col> */}
                            </Row>

                        </Col>
                    </Row>
                </Card>
            </PageContainer>
        );
    }
}

export default Index;
